﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using iTunesLib;

namespace SensorDetection
{
    class iTunesSensor : Sensor, IObserver
    {
        iTunesApp app;
        private bool isEnabled;
        public bool enabled()
        {
            return isEnabled;
        }
        public iTunesSensor()
        {
            name = "iTunes Sensor";
            isEnabled = false;
            Process[] proc = System.Diagnostics.Process.GetProcesses(Environment.MachineName);
            //Enable this sensor if iTunes is a running process
            foreach (Process p in proc)
            {
                if (p.ProcessName.ToString().Equals("iTunes"))
                {
                    isEnabled = true;
                    break;
                }
            }
            if (isEnabled)
            {
                InitializeApp();
            }
        }
        //Designed to be sent only by the processSensor, gives array of running processes
        //Checks to see if iTunes is one of the new processes
        public void Update(string sender, object msg)
        {
            if (!isEnabled)//only run if sensor is disabled
            {
                Console.WriteLine("Process event detected from iTunes class");
                Process[] proc = (Process[])msg;
                bool enableThis = false;
                foreach (Process p in proc)
                {
                    if (p.ProcessName.ToString().Equals("iTunes"))
                    {
                        enableThis = true;
                        Console.WriteLine("iTunes Opened");
                        InitializeApp();
                        break;
                    }
                }
                isEnabled = enableThis;
            }
        }
        //Create new iTunesApp, create event handler
        public void InitializeApp()
        {
            app = new iTunesAppClass();
            app.OnPlayerPlayEvent += new _IiTunesEvents_OnPlayerPlayEventEventHandler(app_OnPlayerPlayEvent);
        }
        //Notify Observer when track changes
        public void app_OnPlayerPlayEvent(object iTrack)
        {
            Console.WriteLine("TRACK CHANGED");
            data = iTrack;
            Notify();
        }
    }
}
